package edu.st.selenium.pages;

import static org.openqa.selenium.support.ui.ExpectedConditions.presenceOfElementLocated;
import static org.openqa.selenium.support.ui.ExpectedConditions.stalenessOf;

import org.openqa.selenium.By;
import org.openqa.selenium.Keys;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.FindBy;
import org.openqa.selenium.support.ui.ExpectedCondition;

public class MovieListPage extends InternalPage {
	
	public MovieListPage(PageManager pages) {
		super(pages);
	}
	
	public MovieListPage ensurePageLoaded() {
		    super.ensurePageLoaded();
		    wait.until(presenceOfElementLocated(By.cssSelector("img[title='Update all']")));
		    return this;
	}
	
	  @FindBy(id = "q")
	  private WebElement searchField;
	  
	  @FindBy(css = "img[title='Add movie']")
	  private WebElement addMovieLink;
	  
	  @FindBy (css = ".movie_box")
	  private WebElement firstMovieLink;
	  
	  @FindBy (css = ".content")
	  private WebElement nothingFoundResult;
	  
	  @FindBy (css = "#results .title")
	  private WebElement firstResultTitle;
	  
	  private WebElement results;
	  
	  public NewMoviePage clickAddMovieLink(){
		  addMovieLink.click();
		  return pages.newMoviePage;
	  }
	  
	  public MovieListPage setSearchField(String text){
		  searchField.sendKeys(Keys.CONTROL + "a");
		  searchField.sendKeys(Keys.DELETE);
		  searchField.sendKeys(text);
		  return this;
	  }
	  	  
	  public MovieListPage doSearch(){
		  searchField.sendKeys(Keys.RETURN);
		  return this;
	  }
	  
	  public MovieListPage getResults(){
		  this.results = driver.findElement(By.cssSelector("div#results a"));
		  return this;
	  }
	  
	  public MovieListPage waitForNewResult(){
		  wait.until(stalenessOf(this.results));
		  return this;
	  }
	  
	  public MovieListPage waitForListToLoad(){
		  wait.until(presenceOfElementLocated(By.cssSelector(".movie_box")));
		  return this;
	  }
	  
	  public MoviePage openFirstMovie() {
			firstMovieLink.click();
			return pages.moviePage;		
		}

	public String getBlankResultText() {
		return nothingFoundResult.getText();
	}

	public String getFirstResultTitle() {
		return firstResultTitle.getText();
	}

}
